import { previewImageUtils, uploadImageUtils } from "../../utils/index";
import { API } from "../../utils/network/api";
import { httpRequest, showContent } from "../../utils/network/network";

const app = getApp();

Component({

  /**
   * 组件的属性列表
   */
  properties: {
    userInfo: {
      type: Object,
      value: {}
    },
    show: {
      type: Boolean,
      value: false
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    templateAvatarUrl: "",
    emptyAvatarUrl: app.globalData.emptyAvatar,
    avatar: "",
    phoneNumber: "",
    userName: "",
    verifyMsg: "",
    remark: "",
  },

  /**
   * 组件的方法列表
   */
  methods: {
    initPopup(val) {
      this.setData({
        visible: val
      })
    },
    onClose() {
      this.setData({
        visible: false
      })
    },
    async updateUserInfo() {
      if (this.data.phoneNumber && this.data.phoneNumber.length != 11) {
        this.setData({
          verifyMsg: "请输入11位手机号"
        })
        return;
      }
      // clear verify msg
      this.setData({
        verifyMsg: ""
      })
      // upload avatar
      uploadImageUtils(this.data.templateAvatarUrl).then(async url => {
        this.data.avatar = url;
        const userInfo = this.properties.userInfo;
        const params = {
          userName: this.data.userName ? this.data.userName : userInfo.userName,
          phoneNumber: this.data.phoneNumber ? this.data.phoneNumber : userInfo.phoneNumber,
          avatar: this.data.avatar ? this.data.avatar : userInfo.avatar,
          remark: this.data.remark ? this.data.remark : userInfo.remark
        }
        // update user info
        const result = await httpRequest(API.updateUserInfo, params, "POST", "application/json");
        this.initData();
        this.triggerEvent("success", result);
      })
        .catch(err => {
          showContent(err);
        })

    },
    afterRead(event) {
      const { file } = event.detail;
      this.setData({
        templateAvatarUrl: file.tempFilePath
      })
    },
    previewImage() {
      previewImageUtils([this.data.templateAvatarUrl || this.data.userInfo.avatar || this.data.emptyAvatarUrl])
    },
    initData() {
      this.setData({
        templateAvatarUrl: "",
        emptyAvatarUrl: app.globalData.emptyAvatar,
        avatar: "",
        phoneNumber: "",
        userName: "",
        verifyMsg: "",
        remark: "",
      })
    },
  },
  observers: {
    show: function (val) {
      this.initPopup(val);
    }
  }
})